<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://chenjiabing666.github.io/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="code-ltfpVmGDr3" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="杂谈," />





  <link rel="alternate" href="/atom.xml" title="不才陈某技术博客" type="application/atom+xml" />






<meta name="description" content="前言
Redis目前已经成为主流的内存数据库了，但是大部分人仅仅是停留在会用的阶段，你真的了解Redis内部的工作原理吗？
今天这篇文章将为大家介绍Redis持久化的两种方案，文章将会从以下五个方面介绍：
什么是RDB，RDB如何实现持久化？
什么是AOF，AOF如何实现持久化？
AOF和RDB的区别。
如何重启恢复数据？
持久化性能问题和解决方案RDB


RDB持久化是把当前进程数据生成快照保">
<meta property="og:type" content="article">
<meta property="og:title" content="一文搞懂Redis持久化">
<meta property="og:url" content="https://chenjiabing666.github.io/2020/04/20/一文搞懂Redis持久化/index.html">
<meta property="og:site_name" content="不才陈某技术博客">
<meta property="og:description" content="前言
Redis目前已经成为主流的内存数据库了，但是大部分人仅仅是停留在会用的阶段，你真的了解Redis内部的工作原理吗？
今天这篇文章将为大家介绍Redis持久化的两种方案，文章将会从以下五个方面介绍：
什么是RDB，RDB如何实现持久化？
什么是AOF，AOF如何实现持久化？
AOF和RDB的区别。
如何重启恢复数据？
持久化性能问题和解决方案RDB


RDB持久化是把当前进程数据生成快照保">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/RDB%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/AOF%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/%E6%96%87%E4%BB%B6%E9%87%8D%E5%86%99%E6%B5%81%E7%A8%8B.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/%E5%90%AF%E5%8A%A8%E6%81%A2%E5%A4%8D.png">
<meta property="og:updated_time" content="2020-04-20T09:00:11.604Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="一文搞懂Redis持久化">
<meta name="twitter:description" content="前言
Redis目前已经成为主流的内存数据库了，但是大部分人仅仅是停留在会用的阶段，你真的了解Redis内部的工作原理吗？
今天这篇文章将为大家介绍Redis持久化的两种方案，文章将会从以下五个方面介绍：
什么是RDB，RDB如何实现持久化？
什么是AOF，AOF如何实现持久化？
AOF和RDB的区别。
如何重启恢复数据？
持久化性能问题和解决方案RDB


RDB持久化是把当前进程数据生成快照保">
<meta name="twitter:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/RDB%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chenjiabing666.github.io/2020/04/20/一文搞懂Redis持久化/"/>





  <title>一文搞懂Redis持久化 | 不才陈某技术博客</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不才陈某技术博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信公众号：码猿技术专栏</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenjiabing666.github.io/2020/04/20/一文搞懂Redis持久化/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="不才陈某">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不才陈某技术博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">一文搞懂Redis持久化</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-20T16:59:42+08:00">
                2020-04-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/杂谈/" itemprop="url" rel="index">
                    <span itemprop="name">杂谈</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/04/20/一文搞懂Redis持久化/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/04/20/一文搞懂Redis持久化/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
		  
		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
			

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  10
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><ul>
<li>Redis目前已经成为主流的内存数据库了，但是大部分人仅仅是停留在会用的阶段，你真的了解Redis内部的工作原理吗？</li>
<li>今天这篇文章将为大家介绍Redis持久化的两种方案，文章将会从以下五个方面介绍：<ol>
<li><strong>什么是RDB，RDB如何实现持久化？</strong></li>
<li><strong>什么是AOF，AOF如何实现持久化？</strong></li>
<li><strong>AOF和RDB的区别。</strong></li>
<li><strong>如何重启恢复数据？</strong></li>
<li><strong>持久化性能问题和解决方案</strong><h2 id="RDB"><a href="#RDB" class="headerlink" title="RDB"></a>RDB</h2></li>
</ol>
</li>
<li>RDB持久化是把当前进程数据生成快照保存到硬盘的过程， 触发RDB持久化过程分为手动触发和自动触发。</li>
<li>RDB完成后会自动生成一个文件，保存在<code>dir</code>配置的指定目录下，文件名是<code>dbfileName</code>指定。</li>
<li>Redis默认会采用LZF算法对生成的RDB文件做压缩处理，压缩后的文件远远小于内存大小，默认开启。</li>
</ul>
<h3 id="手动触发"><a href="#手动触发" class="headerlink" title="手动触发"></a>手动触发</h3><ul>
<li>手动触发的命令有<code>save</code>和<code>bgsave</code>。</li>
<li><code>save</code>：该命令会阻塞Redis服务器，直到RDB的过程完成，已经被废弃，因此线上不建议使用。</li>
<li><code>bgsave</code>：每次进行RDB过程都会fork一个子进程，由子进程完成RDB的操作，因此阻塞只会发生在fork阶段，一般时间很短。</li>
</ul>
<h3 id="自动触发"><a href="#自动触发" class="headerlink" title="自动触发"></a>自动触发</h3><ul>
<li>除了手动触发RDB，Redis服务器内部还有如下几个场景能够自动触发RDB：<ol>
<li>根据我们的 <code>save m n</code> 配置规则自动触发。</li>
<li>如果从节点执行全量复制操作， 主节点自动执行bgsave生成RDB文件并发送给从节点。</li>
<li>执行<code>debug reload</code>命令重新加载Redis时， 也会自动触发save操作。</li>
<li>默认情况下执行shutdown命令时， 如果没有开启AOF持久化功能则自动执行<code>bgsave</code>。</li>
</ol>
</li>
</ul>
<h3 id="RDB执行流程"><a href="#RDB执行流程" class="headerlink" title="RDB执行流程"></a>RDB执行流程</h3><ul>
<li>RDB的主流方式就是bgsave，通过下图我们来看看RDB的执行流程：<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/RDB%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B.png" alt="RDB执行流程"></li>
<li>通过上图可以很清楚RDB的执行流程，如下：<ol>
<li>执行bgsave命令后，会先判断是否存在AOF或者RDB的子进程，如果存在，直接返回。</li>
<li>父进程fork操作创建一个子进程，fork操作中父进程会被阻塞。</li>
<li>fork完成后，子进程开始根据父进程的内存生成临时快照文件，完成后对原有的RDB文件进行替换。执行<code>lastsave</code>命令可以查看最近一次的RDB时间。</li>
<li>子进程完成后发送信号给父进程，父进程更新统计信息。</li>
</ol>
</li>
</ul>
<h3 id="RDB的优点"><a href="#RDB的优点" class="headerlink" title="RDB的优点"></a>RDB的优点</h3><ul>
<li>RDB是一个紧凑压缩的二进制文件， 代表Redis在某个时间点上的数据快照。 非常适用于备份， 全量复制等场景。 比如每6小时执行<code>bgsave</code>备份，并把RDB文件拷贝到远程机器或者文件系统中，用于灾难恢复。</li>
<li>Redis加载<code>RDB</code>恢复数据远远快于<code>AOF</code>的方式。</li>
</ul>
<h3 id="RDB的缺点"><a href="#RDB的缺点" class="headerlink" title="RDB的缺点"></a>RDB的缺点</h3><ul>
<li>RDB方式数据没办法做到<code>实时持久化</code>/<code>秒级持久化</code>。 因为bgsave每次运行都要执行fork操作创建子进程，属于重量级操作，频繁执行成本过高。</li>
<li>RDB文件使用特定二进制格式保存， Redis版本演进过程中有多个格式的RDB版本， 存在老版本Redis服务无法兼容新版RDB格式的问题。</li>
</ul>
<h2 id="AOF"><a href="#AOF" class="headerlink" title="AOF"></a>AOF</h2><ul>
<li><code>AOF</code>（append only file） 持久化： 以独立日志的方式记录每次写命令，重启时再重新执行AOF文件中的命令达到恢复数据的目的。 AOF的主要作用是解决了数据持久化的实时性， 目前已经是Redis持久化的<code>主流方式</code>。</li>
</ul>
<h3 id="如何开启AOF"><a href="#如何开启AOF" class="headerlink" title="如何开启AOF"></a>如何开启AOF</h3><ul>
<li>开启AOF功能需要设置配置：<code>appendonly yes</code>， 默认不开启。 AOF文件名通过<code>appendfilename</code>配置设置， 默认文件名是<code>appendonly.aof</code>。 保存路径同RDB持久化方式一致，通过<code>dir</code>配置指定。 </li>
</ul>
<h3 id="AOF整体的执行流程"><a href="#AOF整体的执行流程" class="headerlink" title="AOF整体的执行流程"></a>AOF整体的执行流程</h3><ul>
<li>AOF执行的流程大致分为<code>命令写入</code>、<code>文件同步</code>、<code>文件重写</code>、<code>重启加载</code>四个步骤，如下图：<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/AOF%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B.png" alt="AOF执行流程"></li>
<li>从上图大致了解了AOF的执行流程，下面一一分析上述的四个步骤。</li>
</ul>
<h3 id="命令写入"><a href="#命令写入" class="headerlink" title="命令写入"></a>命令写入</h3><ul>
<li><p>AOF命令写入的内容直接是文本协议格式。 例如<code>set hello world</code>这条命<br>令， 在AOF缓冲区会追加如下文本：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">*<span class="number">3</span>\r\n$<span class="number">3</span>\r\nset\r\n$<span class="number">5</span>\r\nhello\r\n$<span class="number">5</span>\r\nworld\r\n</div></pre></td></tr></table></figure>
</li>
<li><p>命令写入是直接写入到AOF的缓冲区中，至于为什么？原因很简单，Redis使用单线程响应命令，如果每次写AOF文件命令都直接追加到硬盘， 那么性能完全取决于当前硬盘负载。先写入缓冲区<code>aof_buf</code>中， 还有另一个好处， Redis可以提供多种缓冲区<br>同步硬盘的策略，在性能和安全性方面做出平衡。</p>
</li>
</ul>
<h3 id="文件同步"><a href="#文件同步" class="headerlink" title="文件同步"></a>文件同步</h3><ul>
<li>Redis提供了多种AOF缓冲区同步文件策略， 由参数<code>appendfsync</code>控制，如下：<ul>
<li>配置为<code>always</code>时， 每次写入都要同步AOF文件， 在一般的SATA硬盘上，Redis只能支持大约几百TPS写入， 显然跟Redis高性能特性背道而驰，不建议配置。</li>
<li>配置为<code>no</code>，由于操作系统每次同步AOF文件的周期不可控，而且会加大每次同步硬盘的数据量，虽然提升了性能，但数据安全性无法保证。</li>
<li>配置为<code>everysec</code>（默认的配置），是<strong>建议的同步策略</strong>， 也是默认配置，做到兼顾性能和数据安全性。理论上只有在系统突然宕机的情况下丢失1秒的数据（当然，这是不太准确的）。</li>
</ul>
</li>
</ul>
<h3 id="文件重写机制"><a href="#文件重写机制" class="headerlink" title="文件重写机制"></a>文件重写机制</h3><ul>
<li>随着命令不断写入AOF， 文件会越来越大， 为了解决这个问题， Redis引入AOF重写机制压缩文件体积。 AOF文件重写是把Redis进程内的数据转化为写命令同步到新AOF文件的过程。</li>
<li><strong>为什么要文件重写呢？</strong> 因为文件重写能够使得AOF文件的体积变得更小，从而使得可以更快的被Redis加载。</li>
<li>重写过程分为手动触发和自动触发。<ul>
<li>手动触发直接使用<code>bgrewriteaof</code>命令。</li>
<li>根据<code>auto-aof-rewrite-min-size</code>和<code>auto-aof-rewrite-percentage</code>参数确定自动触发时机。</li>
</ul>
</li>
<li><code>auto-aof-rewrite-min-size</code>：表示运行AOF重写时文件最小体积， 默认为64MB。</li>
<li><code>auto-aof-rewrite-percentage</code>：代表当前AOF文件空间（<code>aof_current_size</code>） 和上一次重写后AOF文件空间（<code>aof_base_size</code>） 的比值。</li>
<li>自动触发时机相当于<strong>aof_current_size&gt;auto-aof-rewrite-minsize&amp;&amp;（aof_current_size-aof_base_size） /aof_base_size&gt;=auto-aof-rewritepercentage</strong>。其中<code>aof_current_size</code>和<code>aof_base_size</code>可以在<code>info Persistence</code>统计信息中查看。</li>
<li><strong>那么文件重写后的AOF文件为什么会变小呢？</strong> 有如下几个原因：<ol>
<li>进程内已经超时的数据将不会再次写入AOF文件中。</li>
<li>旧的AOF文件含有无效命令，如<code>del key1</code>、 <code>hdel key2</code>等。重写使用进程内数据直接生成，这样新的AOF文件只保留最终数据的写入命令。</li>
<li>多条写命令可以合并为一个， 如：<code>lpush list a</code>、 <code>lpush list b</code>、<code>lpush listc</code>可以转化为：<code>lpush list a b c</code>。为了防止单条命令过大造成客户端缓冲区溢出，对于<code>list</code>、 <code>set</code>、 <code>hash</code>、 <code>zset</code>等类型操作，以64个元素为界拆分为多条。</li>
</ol>
</li>
<li>介绍了文件重写的系列知识，下面来看看Redis内部是如何进行文件重写的，如下图：<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/%E6%96%87%E4%BB%B6%E9%87%8D%E5%86%99%E6%B5%81%E7%A8%8B.png" alt="文件重写"></li>
<li>看完上图，大致了解了文件重写的流程，对于重写的流程，补充如下：<ol>
<li>重写期间，主线程并没有阻塞，而是在执行其他的操作命令，依然会向旧的AOF文件写入数据，这样能够保证备份的最终完整性，如果数据重写失败，也能保证数据不会丢失。</li>
<li>为了把重写期间响应的写入信息也写入到新的文件中，因此也会为子进程保留一个缓冲区，防止新写的文件丢失数据。</li>
<li>重写是直接把当前内存的数据生成对应命令，并不需要读取老的AOF文件进行分析、命令合并。</li>
<li>AOF文件直接采用的<code>文本协议</code>，主要是兼容性好、追加方便、可读性高可认为修改修复。</li>
<li>无论是<code>RDB</code>还是<code>AOF</code>都是先写入一个临时文件，然后通过<code>重命名</code>完成文件的替换。</li>
</ol>
</li>
</ul>
<h3 id="AOF的优点"><a href="#AOF的优点" class="headerlink" title="AOF的优点"></a>AOF的优点</h3><ul>
<li>使用 AOF 持久化会让 Redis 变得非常耐久：你可以设置不同的 fsync 策略，比如无 fsync ，每秒钟一次 fsync ，或者每次执行写入命令时 fsync 。 AOF 的默认策略为每秒钟 fsync 一次，在这种配置下，Redis 仍然可以保持良好的性能，并且就算发生故障停机，也最多只会丢失一秒钟的数据（ fsync 会在后台线程执行，所以主线程可以继续努力地处理命令请求）。</li>
</ul>
<h3 id="AOF的缺点"><a href="#AOF的缺点" class="headerlink" title="AOF的缺点"></a>AOF的缺点</h3><ul>
<li>对于相同的数据集来说，AOF 文件的体积通常要大于 RDB 文件的体积。根据所使用的 fsync 策略，AOF 的速度可能会慢于 RDB。 在一般情况下， 每秒 fsync 的性能依然非常高， 而关闭 fsync 可以让 AOF 的速度和 RDB 一样快， 即使在高负荷之下也是如此。不过在处理巨大的写入载入时，RDB 可以提供更有保证的最大延迟时间。</li>
<li>数据恢复速度相对于RDB比较慢。</li>
</ul>
<h2 id="AOF和RDB的区别"><a href="#AOF和RDB的区别" class="headerlink" title="AOF和RDB的区别"></a>AOF和RDB的区别</h2><ul>
<li>RDB持久化是指在指定的时间间隔内将内存中的数据集快照写入磁盘，实际操作过程是fork一个子进程，先将数据集写入临时文件，写入成功后，再替换之前的文件，用二进制压缩存储。</li>
<li>AOF持久化以日志的形式记录服务器所处理的每一个写、删除操作，查询操作不会记录，以文本的方式记录，可以打开文件看到详细的操作记录。</li>
</ul>
<h2 id="重启加载"><a href="#重启加载" class="headerlink" title="重启加载"></a>重启加载</h2><ul>
<li>无论是RDB还是AOF都可用于服务器重启时的数据恢复，执行流程如下图：<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Redis%E6%8C%81%E4%B9%85%E5%8C%96/%E5%90%AF%E5%8A%A8%E6%81%A2%E5%A4%8D.png" alt="重启加载流程"></li>
<li>上图很清晰的分析了Redis启动恢复数据的流程，先检查AOF文件是否开启，文件是否存在，再检查RDB是否开启，文件是否存在。</li>
</ul>
<h2 id="性能问题与解决方案"><a href="#性能问题与解决方案" class="headerlink" title="性能问题与解决方案"></a>性能问题与解决方案</h2><ul>
<li>通过上面的分析，我们都知道RDB的快照、AOF的重写都需要fork，这是一个重量级操作，会对Redis造成阻塞。因此为了不影响Redis主进程响应，我们需要尽可能降低阻塞。</li>
<li>那么如何减少fork操作的阻塞呢？<ol>
<li>优先使用物理机或者高效支持fork操作的虚拟化技术。</li>
<li>控制Redis实例最大可用内存， fork耗时跟内存量成正比， 线上建议每个Redis实例内存控制在10GB以内。</li>
<li>合理配置Linux内存分配策略，避免物理内存不足导致fork失败。</li>
<li>降低fork操作的频率，如适度放宽AOF自动触发时机，避免不必要的全量复制等。</li>
</ol>
</li>
</ul>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><ul>
<li>本文介绍了Redis持久化的两种不同的策略，大部分内容是运维人员需要掌握的，当然作为后端人员也是需要了解一下，毕竟小公司都是一人搞全栈，哈哈。</li>
<li><strong>如果觉得陈某写的不错，有所收获的话，关注分享一波，你的关注将是陈某写作的最大动力，谢谢支持！！！</strong></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>写的可还行？</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.jpg" alt="不才陈某 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
	<div>
	
<div>
      
        
      
</div>

  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/杂谈/" rel="tag"><i class="fa fa-tag"></i> 杂谈</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/20/Mysql最全面试题/" rel="next" title="Mysql最全面试题">
                <i class="fa fa-chevron-left"></i> Mysql最全面试题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/20/索引的优化/" rel="prev" title="MySQL中索引如何优化？">
                MySQL中索引如何优化？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="不才陈某" />
            
              <p class="site-author-name" itemprop="name">不才陈某</p>
              <p class="site-description motion-element" itemprop="description">本站是不才陈某的技术分享博客。内容涵盖Java后端技术、Spring Boot、微服务架构、系统安全、前端、系统监控等相关的研究与知识分享。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">63</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/1556564194374926" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-globe"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/xiao-ming-64-34-45" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_34162294" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png" target="_blank" title="微信公众号">
                      
                        <i class="fa fa-fw fa-globe"></i>微信公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.pexels.com/zh-cn/" title="Pexels" target="_blank">Pexels</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/" title="纯洁的微笑" target="_blank">纯洁的微笑</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#RDB"><span class="nav-text">RDB</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#手动触发"><span class="nav-text">手动触发</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自动触发"><span class="nav-text">自动触发</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RDB执行流程"><span class="nav-text">RDB执行流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RDB的优点"><span class="nav-text">RDB的优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RDB的缺点"><span class="nav-text">RDB的缺点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AOF"><span class="nav-text">AOF</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#如何开启AOF"><span class="nav-text">如何开启AOF</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AOF整体的执行流程"><span class="nav-text">AOF整体的执行流程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#命令写入"><span class="nav-text">命令写入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件同步"><span class="nav-text">文件同步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件重写机制"><span class="nav-text">文件重写机制</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AOF的优点"><span class="nav-text">AOF的优点</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AOF的缺点"><span class="nav-text">AOF的缺点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#AOF和RDB的区别"><span class="nav-text">AOF和RDB的区别</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重启加载"><span class="nav-text">重启加载</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#性能问题与解决方案"><span class="nav-text">性能问题与解决方案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">不才陈某</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">143.1k</span>
  
</div>

<!--





  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共143.1k字</span>
</div>

        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'RtlQOgOT3M0hgyMeogykSQjT-gzGzoHsz',
        appKey: 'vSCxLU88wnXVf0Pa8mwJrCPm',
        placeholder: '原创不易，欢迎各位指正',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
